<template>
    <div>
        <a-button type="primary" @click="importClick">
            导入
        </a-button>
        <vxe-modal v-model="state.visible" v-bind="state.config" @close="closeModel" @hide="closeModel">
            <template #title> 导入 </template>
            <template #default>
                <div class="w-full h-full relative p-2 flex flex-col" v-if="!state.loading">
                    <div class="card h-full rounded">
                        <div class="w-full h-full flex flex-col overflow-y-auto p-6 pt-2 pb-8">
                            <div v-show="state.upStatus === undefined" align="center">
                                <a-button @click="downExcel">下载模板</a-button>
                                <div style="margin-top:5px"><span>下载模版后，请按模版要求填写</span></div>
                            </div>
                            <a-upload-dragger v-if="state.upStatus=== undefined" class="avatar-uploader mt-2" @change="handleAvatarSuccess" @drop="handleAvatarSuccess" :data="{'name':props.moduleName}" :action="state.action" :headers="state.headers" :multiple="false" :showUploadList="false" accept=".xls,.xlsx">
                                <div>
                                    <p class="ant-upload-drag-icon">
                                        <my-icon type="system-shangchuan1" />
                                    </p>
                                    <p class="ant-upload-text">上传文件</p>
                                </div>
                            </a-upload-dragger>
                            <div v-else-if="state.upStatus=== 0">
                                <div>
                                    <a-result status="info" title="正在导入...">
                                        <template #extra>
                                            <div class="flex justify-around mt-12">
                                                <div>
                                                    失败：<b style="font-size:18px;color:red;font-weight: 700;">{{state.errorCount}}</b> 条
                                                </div>
                                                <div>
                                                    增加：<b style="font-size:18px;font-weight: 700;">{{state.insertCount}}</b> 条
                                                </div>
                                                <div>
                                                    更新：<b style="font-size:18px;font-weight: 700;">{{state.updateCount}}</b> 条
                                                </div>
                                            </div>
                                        </template>
                                    </a-result>
                                </div>

                            </div>
                            <div v-else-if="state.upStatus===1">
                                <div>
                                    <a-result status="success" title="导入完成">
                                        <template #extra>
                                            <a-button key="console" type="primary" @click="state.upStatus = undefined">继续上传</a-button>
                                            <a-button key="buy" @click="closeModel">关闭</a-button>
                                        </template>
                                    </a-result>
                                </div>
                                <div class="flex justify-around">
                                    <div>
                                        失败：<b style="font-size:18px;color:redfont-weight: 700;">{{state.errorCount}}</b> 条
                                    </div>
                                    <div>
                                        增加：<b style="font-size:18px;font-weight: 700;">{{state.insertCount}}</b> 条
                                    </div>
                                    <div>
                                        更新：<b style="font-size:18px;font-weight: 700;">{{state.updateCount}}</b> 条
                                    </div>
                                </div>
                            </div>
                            <div v-else>
                                <div>
                                    <!-- <a-alert message="导入失败，请下载失败文件查看详情" type="error" /> -->
                                    <a-result status="error" title="导入失败，请下载失败文件查看详情">
                                        <template #extra>
                                            <a-button key="console" type="primary" @click="downFile">点击下载</a-button>
                                        </template>
                                    </a-result>
                                </div>
                                <div class="flex justify-around">
                                    <div>
                                        失败：<b style="font-size:18px;color:red; font-weight: 700;">{{state.errorCount}}</b> 条
                                    </div>
                                    <div>
                                        增加：<b style="font-size:18px;font-weight: 700;">{{state.insertCount}}</b> 条
                                    </div>
                                    <div>
                                        更新：<b style="font-size:18px;font-weight: 700;">{{state.updateCount}}</b> 条
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <div v-else class="flex-center">
                    <a-spin />
                </div>
            </template>
            <template #footer>
                <div class="p-3 text-center" v-if="false">
                    <a-space :size="10">
                        <a-button type="primary">提交</a-button>
                        <a-button>取消</a-button>
                    </a-space>
                </div>
            </template>
        </vxe-modal>
    </div>
</template>
<script setup>
const emits = defineEmits(['change', 'update:value'])
const props = defineProps({
    moduleName: {
        type: String,
        default: '测试',
    },
})
const state = reactive({
    config: XEUtils.clone(modelConfig, true),
    upStatus: undefined, //导入状态
    taskId: 0, //任务ID
    setInterval: undefined, //定时器
    action: isDev ? '/api/api/excel/uploadFile' : '/api/excel/uploadFile',
    headers: {
        access_token: useStore().token,
    },
})

//下载失败的文件
function downFile() {
    axios.postFile('/api/excel/downloadFailResult', { id: state.taskId }).then(res => {
        message.success('导入失败文件会以工作通知发送给您')
    })
    closeModel()
}
//文件上传成功时的钩子
function handleAvatarSuccess(res) {
    if (res.file.status == 'done') {
        state.taskId = res.file.response.data
        getimportAssetResult()
        state.setInterval = setInterval(() => {
            getimportAssetResult()
        }, 500)
    }
    if (res.file.status == 'error') {
        message.warning(res.file.response.message)
    }
}
function getimportAssetResult() {
    axios
        .postForm('/api/excel/queryUploadResult', { id: state.taskId })
        .then(res => {
            state.errorCount = res.data.errorCount
            state.insertCount = res.data.insertCount
            state.updateCount = res.data.updateCount
            // 0导入中  1导入成功  2导入失败
            if (res.data.status === 'RUNNING') {
                state.upStatus = 0
            } else if (res.data.status === 'SUCCESS') {
                state.upStatus = 1
                clearInterval(state.setInterval)
            } else {
                state.upStatus = 2
                clearInterval(state.setInterval)
            }
        })
        .catch(err => {
            if (state.setInterval) clearInterval(state.setInterval)
        })
}

//下载导入模板
function downExcel() {
    axios.postFile(`/api/excel/downloadTemplate?name=${props.moduleName}`).then(res => {
        const contentDisposition = res.headers['content-disposition']
        var filename = contentDisposition.match(/filename=([^;]+)/)[1]
        const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 'application/vnd.ms-excel',
        })
        const url = window.URL.createObjectURL(blob)
        // 创建a标签
        const ele = document.createElement('a')
        ele.style.display = 'none'
        ele.href = url
        ele.download = decodeURIComponent(filename) || 'downFile.xlsx'
        document.querySelectorAll('body')[0].appendChild(ele)
        ele.click()
        ele.remove()
    })
}

// 点击导入按钮
function importClick() {
    //窗口配置
    state.config.id = '导入'
    state.config.remember = false
    state.config.width = '600px'
    state.config.height = '420px'
    state.visible = true
    state.loading = false
}

function closeModel() {
    state.loading = true
    state.visible = false
    state.upStatus = undefined
    if (state.setInterval) clearInterval(state.setInterval)
}

defineExpose({
    closeModel,
})
const {} = toRefs(state)
</script>
<style>
.avatar-uploader {
    height: 100%;
}
.avatar-uploader .ant-upload-drag .ant-upload-btn {
    display: flex;
    justify-content: center;
    align-items: center;
}
.avatar-uploader .ant-upload-drag {
    border: 3px dashed #dedede;
}
.ant-result-title {
    font-size: 20px !important;
}
</style>